
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
 */
package be.ac.ua.pats.thesisrobotica.robot.RR.sensors.listeners;

//~--- non-JDK imports --------------------------------------------------------

import be.ac.ua.pats.thesisrobotica.robot.RR.sensors.utils.InterrupterThread;

import lejos.nxt.SensorPort;

/**
 *
 * @author Admin
 */
public abstract class UltrasonicSensorListener extends SensorListener {
    final lejos.nxt.UltrasonicSensor ultrasonicSensor;
    int previousDistance;
    int currentDistance;

    public UltrasonicSensorListener(SensorPort port, long interval, long threshold) {
        super(port, interval, threshold);
        ultrasonicSensor  = new lejos.nxt.UltrasonicSensor(port);
        /**
        interrupterThread = new InterrupterThread(this) {
            @Override
            public void start() {
                while (isBlocked()) {}

                int currentDistance = ultrasonicSensor.getDistance();

                while (currentDistance == ultrasonicSensor.getDistance()) {}

                interruptThread();
            }
        };
         * **/

        this.start();
    }

    public abstract void stateChanged();

    @Override
    public void run() {
        interrupterThread.start();

        while (true) {
            if (threshold == 0) {
                try {
                    interrupterThread.setBlocked(false);
                    Thread.sleep(interval);
                    interrupterThread.setBlocked(true);
                    stateChanged();
                } catch (InterruptedException ex) {}
            } else {
                try {
                    interrupterThread.setBlocked(false);
                    Thread.sleep(interval);
                    interrupterThread.setBlocked(true);
                    currentDistance = ultrasonicSensor.getDistance();
                    if((currentDistance + threshold) > previousDistance ||
                            (currentDistance + threshold) < previousDistance) {
                        previousDistance = currentDistance;
                        stateChanged();
                    }
                } catch (InterruptedException ex) {}
            }
        }
    }
}
